const app = getApp();
const util = require('../../utils/util.js');
const request = require("../../utils/request.js").request;
const url = require("../../utils/request.js").commonUrl;
const collectActivity = require("../../utils/util.js").collectActivity;
const collectRequest = require("../../utils/util.js").collectRequest;
const collectUtil = require("../../utils/collect-util.js");


const now = new Date();
const nowTime = now.getTime();
const day = now.getDay();
const oneDayTime = 24 * 60 * 60 * 1000;
const nowMonth = now.getMonth();           //当前月   
let nowYear = now.getYear();             //当前年   
nowYear += (nowYear < 2000) ? 1900 : 0;
//获取周一或者周末日期
function week(mondy) {
    //显示周一
    const MondayTime = nowTime - (day - 1) * oneDayTime;
    //显示周日
    const SundayTime = nowTime + (7 - day) * oneDayTime;
    if (mondy) {
        return MondayTime
    }
    return SundayTime
}


//获得某月的天数   
function getMonthDays(myMonth) {
    const monthStartDate = new Date(nowYear, myMonth, 1);
    const monthEndDate = new Date(nowYear, myMonth + 1, 1);
    const days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
    return days;
}

//获取明天日期
function tomorrow() {
    const tomorrow = now.getTime() + 24 * 60 * 60 * 1000;
    return tomorrow
}
//获取本月起始和结束日期

function month(start) {

    //起始
    const monthStartDate = new Date(nowYear, nowMonth, 1);
    //结束
    const monthEndDate = new Date(nowYear, nowMonth, getMonthDays(nowMonth));

    if (start) {
        return monthStartDate
    }
    return monthEndDate

}


//日期格式化
Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+":  this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}
//new Date().format('yy-M-d h:m:s'); // 18-1-25 22:18:17
const staps = [
    { id: "0", text: "今日", time: "today" },
    { id: "1", text: "明日", time: "tomorrow" },
    { id: "2", text: "本周末", time: "sunday" },
    { id: "3", text: "一周内", time: "week" },
    { id: "4", text: "一月内", time: "month" }
]

let size = 5;
let num = 1;
var latitude, longitude;
let openid;
let refreshEnable, moreEnable;
var keyword;

let sort = "distanceSort";
const highLight = ["selected", "", ""];
const navItem = [
    { id: "0", title: "距离优先", sortType: "distanceSort" },
    { id: "1", title: "智能排序", sortType: 'weightSort' },
    { id: "2", title: "人气最高", sortType: 'interestSort' }
]
var target;

Page({

    /**
     * 页面的初始数据
     */
    data: {
        url: url,
        startDate: "",
        endDate: "",
        selOp: [],
        copData: navItem,
        modal: false,
        fiter: false,
        open: false,
        choseOp: [],
        current: { id: "0", title: "距离优先" },
        resetAc: false,
        confirmAc: true,
        labelTypes: "",
        list: [],
        hasMore: true,
        tab1: true,
        tab2: false,
        staps: staps,
        timeOp: []
    },

    bindStartDateChange: function (e) {
        this.setData({
            startDate: e.detail.value
        })
    },
    bindEndDateChange: function (e) {
        this.setData({
            endDate: e.detail.value
        })
    },
    //收藏活动点
    like: function (event) {
        let that = this;
        util.isLogin(function () {
            let result = [];
            let index = event.currentTarget.dataset.index;
            let value = !that.data.list[index].interest;
            // let interestParam = {}, countParam = {};

            const params = {
                "activityId": that.data.list[index].activityId, //活动点ID
                "weixin": openid,  //用户ID
                "isInterest": value//是否收藏，true为收藏，false为取消收藏
            };

            //console.log(that.data.list);


            collectRequest(params, function (isInterest, count) {
                let isInterestKey = 'list[' + index + '].interest';
                let isInterestValue = isInterest;
                let countKey = 'list[' + index + '].numberOfInterest';
                let countVal = count;
                let interestParam = {}, countParam = {};
                interestParam[isInterestKey] = isInterestValue;
                countParam[countKey] = countVal;
                //console.log(isInterest, count);

                that.setData(interestParam);
                that.setData(countParam);


            });


            app.globalData.flag = that.data.list[index].activityId;
        })

    },



    //跳转到活动详情页面
    detailGo: function (event) {
        let index = event.currentTarget.dataset.itemid;
        //console.log(this.data.list);
        let activityId = this.data.list[index].activityId;
        let activityAreaId = this.data.list[index].activityAreaId;
        var detailInfo = {
            activityId: activityId,
            activityAreaId: activityAreaId
        }
        this.setData({
            index: index
        })

        wx.navigateTo({
            url: '../details/details?detailInfo=' + JSON.stringify(detailInfo),
            success: function (res) {
            },
            fail: function (res) {
            },
            complete: function (res) {
            }
        })
    },
   
    getList: function (params, type) {
        let that = this;
        if (type == 1) {
            if (!refreshEnable) {
                return
            } else {
                refreshEnable = false;
                moreEnable = false;
            }
            if (!that.data.hasMore) {
                that.setData({
                    hasMore: true
                })
            }
            wx.showNavigationBarLoading();
            request('/m/search/activity.json', params).then(function (res) {
                refreshEnable = true;
                moreEnable = true;
                if (!res.data.result) {
                    res.data.result = [];
                }
                //console.log("res", res.data.result)
                wx.hideNavigationBarLoading();
                if (res.data.result.length < size) {
                    that.setData({
                        list: res.data.result,
                        hasMore: false
                    })
                } else {
                    ++num;
                    that.setData({
                        list: res.data.result,
                        hasMore: true
                    })
                }

                that.addCollectBean();
            })

        }
        else if (type == 2) {
            if (!moreEnable) {
                return
            } else {
                moreEnable = false;
            }
            if (!that.data.hasMore) {
                return
            }
            request('/m/search/activity.json', params).then(function (res) {
                moreEnable = true;
                if (!res.data.result) {
                    res.data.result = [];
                }
                //console.log("more",res)

                if (res.data.result.length < size) {
                    that.setData({
                        hasMore: false,
                        list: that.data.list.concat(res.data.result)
                    })
                } else {
                    ++num;
                    that.setData({
                        list: that.data.list.concat(res.data.result),
                        hasMore: true
                    })

                }

                that.addCollectBean();

            })

        } else {
            request('/m/search/activity.json', params).then(function (res) {
                refreshEnable = true;
                moreEnable = true;
                //console.log(res.data.result);
                if (!res.data.result) {
                    res.data.result = []
                }
                if (res.data.result.length < size) {
                    that.setData({
                        hasMore: false,
                        list: res.data.result
                    })
                } else {
                    ++num;
                    that.setData({
                        list: res.data.result
                    })
                }

                that.addCollectBean();


            })
        }
    },
    addCollectBean: function () {
        let that = this;
        for (let i = 0; i < that.data.list.length; i++) {
            let collectObsBean = new collectUtil.CollectObsBean();
            // console.log(collectObsBean.Tag);
            collectObsBean.tag = collectUtil.Tag.near;
            collectObsBean.activityId = that.data.list[i].activityId;

            collectObsBean.callBack = function CallBack(result) {
                that.data.list[i]["interest"] = result[0];
                that.data.list[i]["numberOfInterest"] = result[1];
                //TODO 改成局部更新
                that.setData(that.data);
                //console.log("addCollectBean", i, that.data.list[i],result);
            };
            collectUtil.addActivity(collectObsBean);
        }
    },
    list: function (e) {
        this.setData({
            tab2: false,
            tab1: true
        })
        if (this.data.open) {
            this.setData({
                open: false,
                modal: false,
                fiter: false
            })
        } else {
            this.setData({
                open: true,
                modal: true,
                fiter: false
            })
        }
    },
    choose: function (e) {
        const that=this;
        for (var i = 0; i < highLight.length; i++) {
            if (highLight[i] == "selected") {
                highLight[i] = ''
            }
        }
        highLight[e.target.dataset.id] = "selected";
        sort = navItem[e.target.dataset.id].sortType;
        num = 1
        var params = {
            weixin: openid,
            leftCorner: (longitude - 5) + "," + (latitude + 5),
            rightCorner: (longitude + 5) + "," + (latitude - 5),
            pageNum: num,
            nowCorner: longitude + "," + latitude,
            pageSize: size,
            keyword: keyword,
            beginTime: that.data.startDate,
            endTime: that.data.endDate,
            sortType: sort
        }
        //console.log("pa", params)
        this.getList(params, 1)
        this.setData({
            current: navItem[e.target.dataset.id],
            selOp: highLight,
            open:false,
            modal: false
        })
    },
    filter: function (e) {
        this.setData({
            tab1: false,
            tab2: true
        })
        if (this.data.fiter) {
            this.setData({
                modal: false,
                fiter: false,
                open: false
            })
        } else {
            this.setData({
                modal: true,
                fiter: true,
                open: false
            })
        }
    },
    //时间快捷选择器
    stap: function (event) {
        const that = this;
        const time = event.currentTarget.dataset.time;
        const index = event.target.dataset.id;
        const timeOp = that.data.timeOp;
        for (var i = 0; i < timeOp.length; i++) {
            if (timeOp[i] == "time-active") {
                timeOp[i] = ""
            }
        }
        timeOp[index] = "time-active";
        //console.log(timeOp)


        that.setData({
            timeOp: timeOp
        })
        switch (time) {
            case "today":
                that.setData({
                    startDate: new Date().format("yyyy-M-d"),
                    endDate: new Date().format("yyyy-M-d")
                })
                break;
            case "tomorrow":
                that.setData({
                    startDate: new Date(tomorrow()).format("yyyy-M-d"),
                    endDate: new Date(tomorrow()).format("yyyy-M-d")
                })
                break;
            case "sunday":
                that.setData({
                    startDate: new Date(week()).format("yyyy-M-d"),
                    endDate: new Date(week()).format("yyyy-M-d")
                })
                break;
            case "week":
                that.setData({
                    startDate: new Date(week("monday")).format("yyyy-M-d"),
                    endDate: new Date(week()).format("yyyy-M-d")
                })
                break;
            case "month":
                that.setData({
                    startDate: new Date(month("start")).format("yyyy-M-d"),
                    endDate: new Date(month()).format("yyyy-M-d")
                })
                break;
        }


    },
    confirm: function () {
        var that = this;
        num = 1;
        var params = {
            weixin: openid,
            leftCorner: (longitude - 5) + "," + (latitude + 5),
            rightCorner: (longitude + 5) + "," + (latitude - 5),
            pageNum: num,
            nowCorner: longitude + "," + latitude,
            pageSize: size,
            keyword: keyword,
            beginTime: that.data.startDate,
            endTime: that.data.endDate,
            sortType: sort
        }
        that.getList(params, 1);
        this.setData({
            resetAc: false,
            modal: false,
            fiter: false,
            confirmAc: true
        })
    },
    reset: function (e) {
        var that = this;
        that.setData({
            startDate: "",
            endDate: '',
            timeOp:[]
        })
    },
    /**
     * 下拉刷新
     */
    refresh: function () {
        var that = this;
        num = 1;
        const params = {
            weixin: openid,
            leftCorner: (longitude - 5) + "," + (latitude + 5),
            rightCorner: (longitude + 5) + "," + (latitude - 5),
            pageNum: num,
            nowCorner: longitude + "," + latitude,
            pageSize: size,
            keyword: keyword,
            beginTime: that.data.startDate,
            endTime: that.data.endDate,
            sortType: sort
        }
        that.getList(params, 1)

    },
    /**
     * 上拉加载
     */
    loadMore: function () {

        var that = this;
        const params = {
            weixin: openid,
            leftCorner: (longitude - 5) + "," + (latitude + 5),
            rightCorner: (longitude + 5) + "," + (latitude - 5),
            pageNum: num,
            nowCorner: longitude + "," + latitude,
            pageSize: size,
            keyword: keyword,
            beginTime: that.data.startDate,
            endTime: that.data.endDate,
            sortType: sort
        }
        that.getList(params, 2)
        
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        if (options.keyword){
            keyword = options.keyword;
        }
        openid = app.globalData.openid;
        //console.log("openid", app.globalData.openid)
        latitude = app.globalData.latitude;
        longitude = app.globalData.longitude;
        const params = {
            weixin: openid,
            leftCorner: (longitude - 5) + "," + (latitude + 5),
            rightCorner: (longitude + 5) + "," + (latitude - 5),
            pageSize: size,
            nowCorner: longitude + "," + latitude,
            sortType: sort,
            pageNum: 1,
            keyword:keyword
        }
        //console.log(params)
        this.getList(params, '');
        this.setData({
            selOp: highLight
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
        return {
            path: "pages/result/result?keyword=" + keyword
        }
    }
})